package com.istock.union.filter;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;

import com.istock.base.common.api.model.ApiBaseResponse;
import com.istock.base.common.api.model.RetStatusEnum;
import com.istock.base.serializer.JsonSerializer;
import com.istock.base.serializer.json.JsonSerializerFactory;
import com.istock.union.user.client.SSOClientUtils;
import com.istock.union.user.filter.AuthorizationCallbackAdapter;
import com.istock.union.user.model.SSOUser;
import com.istock.union.user.model.UserInfo;
import com.istock.union.user.service.UserInfoService;
import com.istock.union.user.utils.WebCommonUtils;

public class PasswdCheckCallback extends AuthorizationCallbackAdapter {

	private Logger logger = LoggerFactory.getLogger(getClass());
	
	private final String REDIRECT_URL = "pre/redirectPage";
	private final String REST_PASSWD_URL = "s/afterLogin/forceResetPwdPre";
	
	@Autowired
	private UserInfoService userInfoService;
	
	@Override
	public boolean preCallback(HttpServletRequest request, HttpServletResponse response, HandlerMethod targetObj) {
		
		final SSOUser ssoUser = SSOClientUtils.getInstance().findCurrentUser();
		//如果用户的密码已经/将要过期,跳转到强制修改密码
		UserInfo userInfo = userInfoService.selectUserDetailsById(ssoUser.getUserId());
		if(!SSOClientUtils.getInstance().isAdmin() && userInfo != null && userInfo.getPasswdExpire() != null && new Date().compareTo(userInfo.getPasswdExpire())>0) {
			logger.info("the user's passwd expired , need to transfer to chage passwd");
			try {
				redirectPage(request, response, REST_PASSWD_URL, "CPWD", "set new password");
			}catch(Exception e) {
				logger.error("return passwd page exception" , e);
			}
			return false;
		}
		return true;
	}
	
	private void redirectPage(HttpServletRequest request , HttpServletResponse response , String url , String ajaxCode , String message) throws Exception {
		if(WebCommonUtils.isAjax(request)) {
			//如果当前请求是ajax
            ApiBaseResponse<Object> apiBaseResponse =
                    new ApiBaseResponse<>(RetStatusEnum.FAIL, ajaxCode, message , null);

            response.setContentType("application/json");
            JsonSerializer serializer = JsonSerializerFactory.findSerializer();
            response.getWriter().println(serializer.serialize(apiBaseResponse));
            response.getWriter().flush();
		}else {
			/*View view = resolver.resolveViewName(REDIRECT_URL, request.getLocale());
			Map<String , Object> paramMap = new HashMap<String , Object>();
			paramMap.put("targetUrl", WebCommonUtils.generateTargetUrl(request.getContextPath(), url));
			view.render(paramMap, request, response);*/
			
			String targetUrl = WebCommonUtils.generateTargetUrl(request.getContextPath() , REDIRECT_URL);
			targetUrl = WebCommonUtils.generateFromUrl(targetUrl, "targetUrl", WebCommonUtils.generateTargetUrl(request.getContextPath(), url));
			response.sendRedirect(targetUrl);
		}
	}

}
